<template>
  <div class="videoBox">
    <audio
        ref="flvPlayerVideo"
        controls
        style="width: 100%; height: 100%; object-fit: fill"
    ></audio>
  </div>
</template>
<script setup name="videoFlv">

import flvjs from 'flv.js';

const flvPlayerVideo = ref(null);
const props = defineProps({
  src: {
    type: String,
    default: "",
  },
  mediaType:{
    type: String,
    default: "mp3"
  }
});

const flvPlayer = ref(null);
const createVideo = () => {
  let url = props.src;
  if(props.mediaType == 'mp3'){
    url = window.location.origin + "/api/mediaFile/" + props.src;
  }
  if (flvjs.isSupported()) {
    const videoElement = flvPlayerVideo.value;
    flvPlayer.value = flvjs.createPlayer(
        {
          cors: true,
          type: props.mediaType,
          url: url, //你的url地址
          isLive: true,
          hasAudio: true
        });
    flvPlayer.value.attachMediaElement(videoElement);
    flvPlayer.value.load();
    //处理视频播放错误的语法
    flvPlayer.value.on('error', () => {
      return false;
    });
  }
};

// 我的视频是弹窗显示的，所以创建了destroy方法，在子组件中暴露出去后，在父组件调用即可，这样关闭弹窗后，视频流会停止请求。
const destroy = () => {
  flvPlayer.value.pause(); //暂停播放数据流
  flvPlayer.value.unload(); //取消数据流加载
  flvPlayer.value.detachMediaElement(); //将播放实例从节点中取出
  flvPlayer.value.destroy(); //销毁播放实例
  flvPlayer.value = null;
};
defineExpose({destroy});

onMounted(() => {
  createVideo();
});
</script>
<style scoped>
.videoBox {
  width: 800px;
  height: 450px;
  border: solid 1px #ccc;
}
</style>